<template>
  <div>
    <div style="margin-bottom: 20px;">
      <el-input v-model="searchQuery" placeholder="请输入用户名进行查询" style="width: 200px; margin-right: 10px;" />
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>
    <el-button type="primary" @click="handleAdd"> 添加用户</el-button>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="角色名称">
        <template #default="scope">
          <div>{{ scope.row.role.roleName }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="180" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button round type="warning" @click="handleUpdate(scope.row)" :disabled="!!scope.row.is_default">更新</el-button>
          <el-popconfirm title="你确定要删除吗?" @confirm="handleDelete(scope.row.id)" confirm-button-text="确定" cancel-button-text="取消">
            <template #reference>
              <el-button round type="danger" :disabled="!!scope.row.is_default">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--    添加对话框-->
    <el-dialog v-model="dialogVisble" title="添加用户">
      <el-form ref="addFormRef" :model="addForm"
               :rules="rules" label-width="80px" class="ruleForm"
               status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"/>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select
              v-model="addForm.roleId"
              placeholder="请选择角色"
              class="m-2"
              size="large"
          >
            <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisble=false">取消</el-button>
          <el-button type="primary" @click="handleAddConfirm()">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!--     更新对话框-->
    <el-dialog v-model="dialogUpdateVisble" title="更新用户">
      <el-form ref="updateFormRef" :model="updateForm"
               :rules="rules" label-width="80px" class="ruleForm"
               status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="updateForm.username"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="updateForm.password" type="password"/>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select
              v-model="updateForm.roleId"
              placeholder="请选择角色"
              class="m-2"
              size="large"
          >
            <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogUpdateVisble=false">取消</el-button>
          <el-button type="primary" @click="handleUpdateConfirm()">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>



<script setup>
import { onMounted, reactive, ref } from "vue";
import axios from "axios";

const tableData = ref([]);
const roleList = ref([]);
const searchQuery = ref(""); // 查询输入框的绑定变量

const getList = async (query = "") => {
  try {
    let res;
    if (query) {
      res = await axios.get(`http://localhost:8000/adminapi/users?username=${query}`);
    } else {
      res = await axios.get('http://localhost:8000/adminapi/users');
    }
    tableData.value = res.data;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

const getRoleList = async () => {
  try {
    let res = await axios.get('http://localhost:8000/adminapi/roles');
    roleList.value = res.data;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

// 显示添加对话框
const handleAdd = () => {
  dialogVisble.value = true;
}
const dialogVisble = ref(false);
const addFormRef = ref();
const addForm = reactive({
  username: "",
  password: "",
  roleId: ""
});
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'blur' },
  ],
})
const handleAddConfirm = () => {
  addFormRef.value.validate(async (valid) => {
    if (valid) {
      dialogVisble.value = false;
      await axios.post('http://localhost:8000/adminapi/users', addForm);
      await getList();
      addForm.username = "";
      addForm.password = "";
      addForm.roleId = "";
    }
  })
}

onMounted(() => {
  getList();
  getRoleList();
})

// 更新
const dialogUpdateVisble = ref(false);
const updateFormRef = ref();
const currentItem = ref();
const updateForm = reactive({
  username: "",
  password: "",
  roleId: ""
});

const handleUpdate = (item) => {
  dialogUpdateVisble.value = true;
  updateForm.username = item.username;
  updateForm.password = item.password;
  updateForm.roleId = item.roleId;
  currentItem.value = item;
}
const handleUpdateConfirm = async () => {
  try {
    dialogUpdateVisble.value = false;
    if (currentItem.value.id !== undefined) {
      await axios.put(`http://localhost:8000/adminapi/users/${currentItem.value.id}`, {
        username: updateForm.username,
        password: updateForm.password,
        roleId: updateForm.roleId
      });
      await getList();
    } else {
      console.error('User ID is undefined');
    }
  } catch (error) {
    console.error('Error updating user:', error.response.data);
  }
};

// 删除
const handleDelete = async (id) => {
  try {
    if (id !== undefined) {
      await axios.delete(`http://localhost:8000/adminapi/users/${id}`);
      await getList();
    } else {
      console.error('User ID is undefined');
    }
  } catch (error) {
    console.error('Error deleting user:', error.response.data);
  }
};

// 查询
const handleSearch = () => {
  getList(searchQuery.value);
}

// 重置
const handleReset = () => {
  searchQuery.value = "";
  getList();
}
</script>
